/*
The MIT License (MIT)

Copyright (c) 2013 Mike Dapiran, Brian May, Richard Pospesel, and Bert Wierenga

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software 
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#pragma once

#include "HashFunctions.h"
#include "EqualityFunctions.h"
#include "Single.h"

namespace Hogshead
{
	namespace Common
	{
		/** 
		* HashSet is an unordered set of objects, implemented as a hash table using linear probing.
		*/
		template <typename Key> class HashSet
		{
		public:
			/**
			* Default constructor with initial size of 100
			*/

			HashSet() : _load_factor(0.5f)
			{
				_hash = HashFunctions::get_hash_function<Key>();
				_equals = EqualityFunctions::get_equality_function<Key>();

				_size = 100;
				_elements = 0;
				_data = new Single<Key>*[_size];
				// null out data bufffer
				memset(_data, 0, sizeof(Single<Key>*) * _size);
			}
			/**
			* Constructor which sets initial size.
			* @param initial_size The initial size of our internal buffer
			*/
			HashSet(int initial_size) : _load_factor(0.5f)
			{
				if(initial_size == 0)
					error("HashSet must have a positive size");

				_hash = HashFunctions::get_hash_function<Key>();
				_equals = EqualityFunctions::get_equality_function<Key>();

				_size = initial_size;
				_elements = 0;
				_data = new Single<Key>*[_size];
				// null out data bufffer
				memset(_data, 0, sizeof(Single<Key>*) * _size);
			}
			/**
			* Copy constructor
			* @param other The hashset to copy.
			*/
			HashSet(const HashSet& other)
			{
				_hash = other._hash;
				_equals = other._equals;

				_size = other._size;
				_elements = other._elements;
				_data = new Single<Key>*[_size];
				for(int k = 0; k < _size; k++)
				{
					if(other._data[k])
						_data[k] = new Single<Key>(*(other._data[k]));
					else
						_data[k] = NULL;
				}
			}

			HashSet(int initial_size, unsigned int (*in_hash)(Key), bool (*in_equals)(Key,Key)) : _load_factor(0.5f)
			{
				if(initial_size == 0)
					error("HashSet must have a positive size");

				_hash = in_hash;
				_equals = in_equals;

				_size = initial_size;
				_elements = 0;
				_data = new Single<Key>*[_size];
				// null out data bufffer
				memset(_data, 0, sizeof(Single<Key>*) * _size);
			}


			~HashSet()
			{
				for(int k = 0; k < _size; k++)
					if(_data[k] != NULL)
						delete _data[k];
				delete[] _data;
			}
			/**
			* Determine if given key is in the set.
			* @param in_key Key to check for
			* @return true if Key is in set, false if not
			*/
			bool contains(Key in_key) const
			{
				for(unsigned int index = _hash(in_key) % _size; _data[index] != NULL; index = (index + 1) % _size)
					if(_equals(_data[index]->first, in_key))
						return true;
				return false;
			}
			/**
			* Add a key to the set.
			* @param in_key Key to add to set.
			* @param returns true if added, false if not added because key already in set.
			*/
			bool add(Key in_key)
			{
				// see if we need to make it bigger
				if(_size * _load_factor <= _elements)
					resize();
				unsigned int index;
				for(index = _hash(in_key) % _size; _data[index] != NULL; index = (index + 1) % _size)
					if(_equals(_data[index]->first, in_key))
						return false;
				_data[index % _size] = new Single<Key>(in_key);
				_elements++;
				return true;
			}

			/**
			* Remove a given key from the set.  Sometimes this is expensive, and must rebuild the entire set.
			* @param in_key Key to remove
			* @return True if removed, False if it was not in the set
			*/
			bool remove(Key in_key)
			{
				if(!contains(in_key))
					return false;

				int key_index = _hash(in_key) % _size;
				
				if(_equals(_data[key_index]->first, in_key) && _data[(key_index + 1) % _size] == NULL )
				{
					delete _data[key_index];
					// if we are here, no linear probing happened on this key, so we can just remove the key
					_data[key_index] = NULL;
					_elements--;
					return true;
				}
				Single<Key>** new_data = new Single<Key>*[_size];
				memset(new_data, 0, sizeof(Single<Key>*) * _size);

				for(int i = 0; i < _size; i++)
				{
					Single<Key>* s = _data[i];
					if(s)
					{
						if(!_equals(s->first, in_key))
						{
							unsigned int index = _hash(s->first);
							while(new_data[index % _size] != NULL)
								index++;
							new_data[index % _size] = s;
						}
						else
							delete s;
					}
				}

				delete[] _data;
				_data = new_data;
				_elements--;
				return true;
			}
			/**
			* Clears the hashset
			*/
			void clear()
			{
				// delete singles
				for(int k = 0; k < _size; k++)
					if(_data[k])
						delete _data[k];
				memset(_data, 0, sizeof(Single<Key>*) * _size);
				_elements = 0;
			}
			/**
			* Returns the size of the 
			*/
			int size() const
			{
				return _elements;
			}
		private:
			/** doubles the size of the buffer */
			void resize()
			{
				int new_size = _size * 2;
				Single<Key>** new_data = new Single<Key>*[new_size];
				// zero out the new buffer
				memset(new_data, 0, sizeof(Single<Key>*) * new_size);
				for(int k = 0; k < _size; k++)
				{ 
					Single<Key>* s = _data[k];
					if(s)
					{
						unsigned int index = _hash(s->first);
						while(new_data[index % new_size] != NULL)
							index++;
						new_data[index % new_size] = s;
					}
				}

				delete[] _data;
				_data = new_data;
				_size = new_size;
			}
			// hash function
			unsigned int (*_hash)(Key);
			// equals function
			bool (*_equals)(Key,Key);

			Single<Key>** _data;
			float _load_factor;
			int _size;
			int _elements;
		};
	}
}